﻿using MediatR;
using System.CJL.API.Application.Command.StorageCommand;
using System.CJL.Domain;
using System.CJL.Domain.DTO;
using System.CJL.Infrstructre.Interface;

namespace System.CJL.API.Application.CommandHanlder.StorageCommandHandler
{
    public class StorageShowCommandHandler:IRequestHandler<StorageShowCommand, PageDTO<Storage>>
    {
        IStorageRepository _storageRepository;

        public StorageShowCommandHandler(IStorageRepository storageRepository)
        {
            _storageRepository = storageRepository;
        }

        public async Task<PageDTO<Storage>> Handle(StorageShowCommand request, CancellationToken cancellationToken)
        {
            var paging = new PageDTO<Storage>();
            var quest = from stor in await _storageRepository.GetAll() where stor.IsDelete == false select stor;
            if (!string.IsNullOrEmpty(request.StorageNumbering))
            {
                quest = quest.Where(p => p.StorageNumbering.Contains(request.StorageNumbering));
            }
            if (!string.IsNullOrEmpty(request.DetailsNumbering))
            {
                quest = quest.Where(p => p.DetailsNumbering.Contains(request.DetailsNumbering));
            }
            if (request.Status!=null)
            {
                quest = quest.Where(p => p.Status == request.Status);
            }
            paging.listcount = quest.Count();
            paging.pagecount = (int)Math.Ceiling((paging.listcount * 1.0) / request.PageSize);
            paging.plist = quest.OrderBy(p => p.StorageId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            return paging;
        }
    }
}
